package com.indsvr.common.utils.sql;

import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;

public class HikariUtils {

    //管理器列表
    private static final HashMap<String,HikariUtils> jdbcUtilsHashMap = new HashMap<>();

    public static Connection getConnection(String url, String user, String pwd) throws SQLException {
        HikariUtils hikariUtils;
        if (jdbcUtilsHashMap.containsKey(url)) {
            hikariUtils = jdbcUtilsHashMap.get(url);
        } else {
            hikariUtils =  new HikariUtils(url, user, pwd);
            jdbcUtilsHashMap.put(url,hikariUtils);
        }
        return hikariUtils.ds.getConnection();
    }


    private DataSource ds;
    private HikariUtils(String url, String user, String pwd) {
        HikariDataSource ds = new HikariDataSource();
        ds.addDataSourceProperty("cachePrepStmts", true);
        ds.addDataSourceProperty("prepStmtCacheSize", 250);
        ds.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
        ds.addDataSourceProperty("useServerPrepStmts", true);
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setJdbcUrl(url);
        ds.setUsername(user);
        ds.setConnectionTestQuery("SELECT 1 FROM DUAL");
        ds.setPassword(pwd);
        ds.setMaximumPoolSize(200);
        ds.setIdleTimeout(60000);
        ds.setMaxLifetime(60000);
        ds.setValidationTimeout(3000);
        ds.setMinimumIdle(200);
        ds.setConnectionTimeout(5000);
        this.ds=ds;
        jdbcUtilsHashMap.put(url,this);
    }


}
